<?php

namespace app\index\controller;

use think\Controller;
use think\Db;

/**
 * 支付回调类
 **/
class Notify extends Controller
{
    /**
     * 回调处理：
     * 1：支付状态改为已支付
     * 2：修改优惠券为已使用状态
     * 3：分佣（分享官，城市合伙人）
     * */
    public function notice()
    {
        $data = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //业务处理代码请自行实现
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {

            //接收附加数据
            $json_attach = $data['attach'];
            $attach_arr = json_decode($json_attach, true);

            //订单号
            $order_sn = $data['out_trade_no'];

            //查询订单支付状态；0：未支付；1：已支付
            $is_pay = Db::name('order')->where(['pay_order_sn' => $order_sn])->value('is_pay');

            if ($is_pay == 0) {
                Db::startTrans();
                try {
                    $this->doGoodsOrder($order_sn);

                    echo 'SUCCESS';
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }

        }
    }

    /**
     * 商品订单支付成功处理业务逻辑
     * @param string $order_sn 支付订单号
     * */
    public function doGoodsOrder($order_sn)
    {
        $order_info = Db::name('order')->where(['pay_order_sn' => $order_sn])->find();

        $order_id = $order_info['id'];
        $user_id = $order_info['user_id'];
        $user_coupon_id = $order_info['user_coupon_id'];

        $time = time();

        $up_user_id = Db::name('user')->where(['id' => $user_id])->value('up_user_id');
        $indirect_user_id = $order_info['indirect_user_id'];

        // 1：修改订单支付状态
        $update_order_data = [
            'is_pay' => 1,
            'status' => $order_info['send_type'] == 1 ? 9 : 2,
            'pay_time' => $time,
            'update_time' => $time
        ];

        $verify_qr = '';
        if ($order_info['send_type'] == 1) {
            // 自提订单，生成核销码
            $qr_info = createVerifyQr($order_id);
            $verify_qr = substr($qr_info['url'], 1);
        }
        $update_order_data['verify_qr'] = $verify_qr;

        Db::name('order')->where(['id' => $order_id])->update($update_order_data);

        // 2：修改优惠券为已使用状态
        if ($user_coupon_id) Db::name('user_coupon')->where(['id' => $user_coupon_id])->update(['status' => 2, 'update_time' => $time]);

        $vice_order_list = Db::name('vice_order')->where(['order_id' => $order_id])->select();
        if ($vice_order_list) {
            $integral_log_data = [];
            $share_integral_log_data = [];
            $send_integral = 0;
            $share_send_integral = 0;
            $indirect_share_send_integral = 0;
            foreach ($vice_order_list as &$v) {
                // 3：增加销量
                Db::name('goods')->where(['id' => $v['goods_id']])->setInc('sales_count', $v['count']);

                // 4：减库存
                Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->setDec('stock', $v['count']);

                // 5：下单人购物得积分
                $goods_integral = Db::name('goods')->where(['id' => $v['goods_id']])->value('send_integral');
                if ($goods_integral) {
                    $send_goods_integral = $goods_integral * $v['count'];

                    $send_integral += $send_goods_integral;

                    $integral_log_data[] = [
                        'user_id' => $user_id,
                        'integral' => $send_goods_integral,
                        'type' => 2,
                        'order_id' => $order_id,
                        'create_time' => $time
                    ];

                    /*// 6：上级用户推广得积分
                    // 分销直推积分比例
                    $share_integral_rate = C('SHARE_INTEGRAL_RATE');
                    $share_send_goods_integral = intval($send_goods_integral * $share_integral_rate / 100);

                    $share_send_integral += $share_send_goods_integral;

                    if ($share_send_goods_integral > 0 && $up_user_id) {
                        // 上级用户获得积分
                        $share_integral_log_data[] = [
                            'user_id' => $up_user_id,
                            'integral' => $share_send_integral,
                            'type' => 3,
                            'order_id' => $order_id,
                            'create_time' => $time
                        ];
                    }

                    // 分销间推积分比例
                    $indirect_share_integral_rate = C('INDIRECT_SHARE_INTEGRAL_RATE');
                    $indirect_share_send_goods_integral = intval($send_goods_integral * $indirect_share_integral_rate / 100);

                    $indirect_share_send_integral += $indirect_share_send_goods_integral;
                    if ($indirect_share_send_goods_integral > 0 && $indirect_user_id) {
                        // 间推用户获得积分
                        $share_integral_log_data[] = [
                            'user_id' => $indirect_user_id,
                            'integral' => $indirect_share_send_integral,
                            'type' => 3,
                            'order_id' => $order_id,
                            'create_time' => $time
                        ];
                    }*/
                }
            }

            if ($integral_log_data) Db::name('integral_log')->insertAll($integral_log_data);
            if ($send_integral) Db::name('user')->where(['id' => $user_id])->setInc('integral', $send_integral);

            if ($share_integral_log_data) Db::name('integral_log')->insertAll($share_integral_log_data);
            if ($share_send_integral) Db::name('user')->where(['id' => $up_user_id])->setInc('integral', $share_send_integral);
            if ($indirect_share_send_integral) Db::name('user')->where(['id' => $indirect_user_id])->setInc('integral', $indirect_share_send_integral);
        }

        // 7：积分扣除
        if ($use_integral = $order_info['use_integral']) {
            $integral_data = [
                'user_id' => $user_id,
                'integral' => '-' . $use_integral,
                'type' => 4,
                'order_id' => $order_id,
                'create_time' => $time
            ];
            Db::name('integral_log')->insert($integral_data);

            Db::name('user')->where(['id' => $user_id])->setDec('integral', $use_integral);
        }
    }

    /**
     * 套餐支付回调
     * */
    public function mealNotice()
    {
        $data = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //业务处理代码请自行实现
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {
            //订单号
            $order_sn = $data['out_trade_no'];

            //查询订单支付状态；0：未支付；1：已支付
            $is_pay = Db::name('order')->where(['pay_order_sn' => $order_sn])->value('is_pay');
            if ($is_pay == 0) {
                Db::startTrans();
                try {
                    $this->doMealOrder($order_sn);

                    echo 'SUCCESS';
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
        }
    }

    /**
     * 套餐订单支付成功处理业务逻辑
     * @param string $order_sn 支付订单号
     * */
    public function doMealOrder($order_sn)
    {
        $order_info = Db::name('order')->where(['pay_order_sn' => $order_sn])->find();

        $order_id = $order_info['id'];
        $user_id = $order_info['user_id'];
        $user_coupon_id = $order_info['user_coupon_id'];

        $time = time();

        // 1：修改订单支付状态
        $update_order_data = [
            'is_pay' => 1,
            'meal_status' => 2,
            'pay_time' => $time,
            'update_time' => $time
        ];
        Db::name('order')->where(['id' => $order_id])->update($update_order_data);

        // 2：修改优惠券为已使用状态
        if ($user_coupon_id) Db::name('user_coupon')->where(['id' => $user_coupon_id])->update(['status' => 2, 'update_time' => $time]);

        $vice_order_list = Db::name('vice_order')->where(['order_id' => $order_id])->select();
        if ($vice_order_list) {
            $integral_log_data = [];
            $send_integral = 0;
            foreach ($vice_order_list as &$v) {
                // 3：增加销量
                Db::name('meal')->where(['id' => $v['meal_id']])->setInc('sales_count', $v['count']);
            }

            if ($integral_log_data) Db::name('integral_log')->insertAll($integral_log_data);
            if ($send_integral) Db::name('user')->where(['id' => $user_id])->setInc('integral', $send_integral);
        }

        // 4：积分扣除 && 生成积分抵扣记录
        if ($use_integral = $order_info['use_integral']) {
            Db::name('user')->where(['id' => $user_id])->setDec('integral', $use_integral);

            $integral_data = [
                'user_id' => $user_id,
                'integral' => '-' . $use_integral,
                'type' => 5,
                'order_id' => $order_id,
                'create_time' => $time
            ];
            Db::name('integral_log')->insert($integral_data);
        }

        // 5：更新用户等级
        updateUserLevel($user_id);

        // 6：上级用户推广得积分
        $pay_price = $order_info['pay_price'];
        $integral_price = $order_info['integral_price'];

        // 直推用户id
        $up_user_id = $order_info['up_user_id'];
        $up_user_info = Db::name('user')->where(['id' => $up_user_id])->find();

        // 间推用户id
        $indirect_user_id = $order_info['indirect_user_id'];
        $indirect_user_info = Db::name('user')->where(['id' => $indirect_user_id])->find();

        // 直推获得积分
        $send_up_integral = 0;
        // 间推获得积分
        $send_indirect_integral = 0;

        // 积分记录数据
        $share_integral_log_data = [];

        // 直推金额下单积分
        if($pay_price){
            $share_price_integral_rate = C('SHARE_PRICE_INTEGRAL_RATE');
            $send_up_integral += intval($pay_price * $share_price_integral_rate / 100);
        }
        // 直推积分下单积分
        if($integral_price){
            $share_integral_integral_rate = C('SHARE_INTEGRAL_INTEGRAL_RATE');
            $send_up_integral +=intval($integral_price * $share_integral_integral_rate / 100);
        }

        if ($send_up_integral > 0 && $up_user_id && $up_user_info['level'] > 1) {
            // 上级用户获得积分
            $share_integral_log_data[] = [
                'user_id' => $up_user_id,
                'integral' => $send_up_integral,
                'type' => 3,
                'order_id' => $order_id,
                'create_time' => $time
            ];

            Db::name('user')->where(['id' => $up_user_id])->setInc('integral', $send_up_integral);

        }

        // 间推金额下单积分
        if($pay_price){
            $indirect_share_price_integral_rate = C('INDIRECT_SHARE_PRICE_INTEGRAL_RATE');
            $send_indirect_integral += intval($pay_price * $indirect_share_price_integral_rate / 100);
        }
        // 间推积分下单积分
        if($integral_price){
            $indirect_share_integral_integral_rate = C('INDIRECT_SHARE_INTEGRAL_INTEGRAL_RATE');
            $send_indirect_integral +=intval($integral_price * $indirect_share_integral_integral_rate / 100);
        }

        if ($send_indirect_integral > 0 && $indirect_user_id && $indirect_user_info['level'] > 2) {
            // 上级用户获得积分
            $share_integral_log_data[] = [
                'user_id' => $indirect_user_id,
                'integral' => $send_indirect_integral,
                'type' => 3,
                'order_id' => $order_id,
                'create_time' => $time
            ];

            Db::name('user')->where(['id' => $indirect_user_id])->setInc('integral', $send_indirect_integral);
        }

        if($share_integral_log_data) Db::name('integral_log')->insertAll($share_integral_log_data);
    }

    /**
     * 余额充值回调
     * */
    public function rechargeNotice()
    {
        $data = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        file_put_contents(RUNTIME_PATH . 'pay.txt', json_encode($data, JSON_UNESCAPED_UNICODE));

        //业务处理代码请自行实现
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {
            //订单号
            $order_sn = $data['out_trade_no'];

            //查询订单支付状态；0：未支付；1：已支付
            $is_pay = Db::name('recharge_order')->where(['order_sn' => $order_sn])->value('is_pay');
            if ($is_pay == 0) {
                Db::startTrans();
                try {
                    $this->doRechargeOrder($order_sn);

                    echo 'SUCCESS';
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
        }
    }

    /**
     * 余额充值回调处理
     * 1：用户余额和积分增加
     * 2：生成余额充值记录
     * 3：生成积分赠送记录
     * */
    public function doRechargeOrder($order_sn)
    {
        $order_info = Db::name('recharge_order')->where(['order_sn' => $order_sn])->find();
        if ($order_info) {
            $user_id = $order_info['user_id'];
            $balance = $order_info['balance'];
            $send_integral = $order_info['send_integral'];

            $time = time();

            $user_info = Db::name('user')->where(['id' => $user_id])->find();

            // 1：用户余额和积分增加
            $user_data = [
                'balance' => $user_info['balance'] + $balance,
                'integral' => $user_info['integral'] + $send_integral
            ];
            Db::name('user')->where(['id' => $user_id])->update($user_data);

            // 2：生成余额充值记录
            $balance_log_data = [
                'user_id' => $user_id,
                'balance' => $balance,
                'order_id' => $order_info['id'],
                'type' => 1,
                'create_time' => $time
            ];
            $balance_id = Db::name('balance_log')->insertGetId($balance_log_data);

            // 3：生成积分赠送记录
            if ($send_integral) {
                $integral_log_data = [
                    'user_id' => $user_id,
                    'integral' => $send_integral,
                    'type' => 1,
                    'balance_id' => $balance_id,
                    'create_time' => $time
                ];
                Db::name('integral_log')->insert($integral_log_data);
            }
        }
    }
}